const classNames = require('classnames')
const _ = require('../utils')
const { buttonBehavior, listItemBehavior } = require('../behaviors')

_.create('button', {
  properties: {
    // types: default, primary, secondary, stable
    type: {
      type: String,
      value: 'default',
    },
    variant: String,
    size: {
      type: String,
      value: 'normal',
    },
    disabled: null,
    outline: null,
    loading: Boolean,
    formType: String,
    pill: null,
  },

  behaviors: ['wx://form-field-button', buttonBehavior, listItemBehavior],

  relations: {
    '../button-group/index': {
      type: 'parent',
      linked: function (target) {
        const { variant, type, size } = target.data
        this.setData({
          variant,
          type,
          size,
        })
      },
    },
  },

  computed: {
    classes(data) {
      const { classPrefix, size, type, variant, disabled, pill, loading, index, isLast } = data
      const classes = classNames(classPrefix, {
        [`${classPrefix}-${type}`]: type !== '',
        [`${classPrefix}-${size}`]: size !== '',
        [`${classPrefix}-disabled`]: disabled,
        [`${classPrefix}-${variant}`]: variant !== '',
        [`${classPrefix}-pill`]: pill,
        [`${classPrefix}-loading`]: loading,
        [`${classPrefix}-group-item`]: index > -1,
        [`${classPrefix}-group-item-first`]: index === 0,
        [`${classPrefix}-group-item-last`]: isLast,
      })

      return classes
    },
  },

  methods: {
    onTap(e) {
      if (this.data.loading) return

      const detail = Object.assign({ index: this.data.index }, e.detail)

      this.triggerEvent('tap', detail, {
        bubbles: true,
        composed: true,
      })
    },
  },

  lifetimes: {
    ready() {},
  },
})
